﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OpenGado.Business.Exceptions;
using OpenGado.DATA.Entities;
using OpenGado.DATA;

namespace OpenGado.Business
{

    /// <summary>
    /// Handles the business logic of purchase orders 
    /// </summary>
    
    public class PurchaseOrderBusiness
    {

        private enum OrderStatus 
        {
            Received, Open, Partial, Canceled
        }


        public void ReceiveOrder (PurchaseOrders orderHeader, List<PurchaseOrderItems> receivedItems)
        {

            bool isPartialOrder = false; 

            // insert the received quantity
                
                // if the quantity received == quantity ordered mark the order complete

            if (receivedItems != null)
                foreach (var r in receivedItems)
                {
                   if (r.Quantity <= r.QuantityReceived)
                   {
                       r.ReceivedStatus = OrderStatus.Received.ToString();

                   }
                   else
                   {
                       r.ReceivedStatus = OrderStatus.Partial.ToString();
                       isPartialOrder = true;
                   }

                   // update the amount in the stock 

                   r.Product.ProductQuantity += r.QuantityReceived;

                   // save the product. 

                   ProductDataControl.Instance.Save(r.Product);

                    // update the purchase order item values . 
                   PurchaseOrderDataControl.Instance.Save(r);
                    
                    if (isPartialOrder)
                    {
                        if (orderHeader != null)
                        {
                             orderHeader.PoStatus = OrderStatus.Partial.ToString();
                        }
                    }
                    else
                    {
                        if (orderHeader != null)
                        {
                            orderHeader.PoStatus = OrderStatus.Received.ToString();
                        }
                    }

                    // save order header. 

                    PurchaseOrderDataControl.Instance.Save(orderHeader);
                }

          
        }

        /// <summary>
        /// Canceles the whole order and its items. 
        /// </summary>
        /// <param name="orderHeader"></param>
        public void CancelOrder(PurchaseOrders orderHeader)
        {
            if (orderHeader != null)
            {
                orderHeader.PoStatus = OrderStatus.Canceled.ToString();
            }

            PurchaseOrderDataControl.Instance.Save(orderHeader);
            
                
        }

        public void AdjustOrder()
        {
            
        }
    }
}
